package com.m.wechathelperforgroup;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    public static final String ACTION_SERVICE_STATE_CHANGE = "ACTION_SERVICE_STATE_CHANGE";
    private TextView textView;
    private ListView listView;
    private Button refreshBtn;
    private Button closeServiceBtn;
    private List<Linkman> linkmens = new ArrayList<>();
    ItemAdapter itemAdapter;
    BroadcastReceiver receiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        receiver = new MainActivity.ServiceStateReceiver();
        textView = findViewById(R.id.textView);
        listView = findViewById(R.id.list);
        refreshBtn = findViewById(R.id.btn_refresh_linkmans);
        refreshBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 刷新联系人列表

            }
        });
        closeServiceBtn = findViewById(R.id.btn_refresh_linkmans);
        closeServiceBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 关闭服务

            }
        });
        itemAdapter = new ItemAdapter(MainActivity.this, R.layout.list_item, linkmens);
        listView.setAdapter(itemAdapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_SERVICE_STATE_CHANGE);
        registerReceiver(receiver, filter);
    }

    private class ServiceStateReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // 建群后刷新未找到的联系人
            linkmens.addAll((List<Linkman>)intent.getSerializableExtra("notFund"));
            itemAdapter.notifyDataSetChanged();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 关闭广播，避免出现异常
        unregisterReceiver(receiver);
    }
}
